import FileSaver from "file-saver";
export default class fileSave {
  /**
   * 导出Excel文件
   * @param {*} res   文件流
   * @param {*} name  文件名
   */
  static getExcel(res, name) {
    const blob: any = new Blob([res], {
      type: "application/vnd.ms-excel",
    });
    FileSaver.saveAs(blob, name + ".xlsx");
  }

  /**
   * 导出CSV文件
   * @param {*} res   文件流
   * @param {*} name  文件名
   */
  static getCsv(res, name) {
    const blob = new Blob([res], {
      type: "application/vnd.ms-excel",
    });
    FileSaver.saveAs(blob, name + ".csv");
  }

  /**
   * 导出图片1
   * @param {*} url 图片地址
   * @param {*} name  文件名
   */
  static getImgURLs(url, name) {
    const last = url.substring(url.lastIndexOf("."), url.length);
    FileSaver.saveAs(url, `${name}${last}`);
  }

  /**
   * 导出图片2
   * @param {*} res 文件流
   * @param {*} name  文件名
   */
  static downLoadImg(res, filename) {
    const blob = new Blob([res], {
      type: "image/jpeg",
    });
    FileSaver.saveAs(blob, `${filename}.jpg`);
  }

  /**
   * base64 转换成 blob
   * @param dataUrl
   * @returns
   */
  static dataURLtoBlob = (dataUrl) => {
    const arr = dataUrl.split(",");
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  };
}
